package org.abc.fund.service.funds;

import org.abc.fund.entity.funds.FundPortfolioItem;
import org.abc.fund.repository.funds.FundPortfolioItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true) // 默认整个类只读，写操作单独标注
public class FundPortfolioItemService {

    @Autowired
    private FundPortfolioItemRepository itemRepository;

    /**
     * 查询某个组合下的所有基金项
     */
    public List<FundPortfolioItem> getItemsByPortfolioId(Long portfolioId) {
        return itemRepository.findByPortfolioId(portfolioId);
    }

    /**
     * 添加单个基金项
     */
    @Transactional
    public FundPortfolioItem addItem(FundPortfolioItem item) {
        return itemRepository.save(item);
    }

    /**
     * 根据 ID 删除某个基金项
     */
    @Transactional
    public void deleteItemById(Long id) {
        itemRepository.deleteById(id);
    }

    /**
     * 批量从组合中移除多个基金（通过 fundCode）
     */
    @Transactional
    public void deleteByPortfolioIdAndCodes(Long portfolioId, List<String> fundCodes) {
        for (String code : fundCodes) {
            itemRepository.deleteByPortfolioIdAndFundCode(portfolioId, code);
        }
    }

    /**
     * 从组合中移除单个基金
     */
    @Transactional
    public void deleteByPortfolioIdAndFundCode(Long portfolioId, String fundCode) {
        itemRepository.deleteByPortfolioIdAndFundCode(portfolioId, fundCode);
    }
}
